<?php

namespace App\Http\Middleware;

use Closure;
use Exception;
use Illuminate\Support\Facades\Request;

/**
 * 解码API请求中的P参数
 * Class RequestDecrypt
 * @package App\Http\Middleware
 */
class RequestDecrypt extends Middleware
{

    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     * @throws Exception
     */
    public function handle(Request $request, Closure $next)
    {
        $p = $request->get('p');
        $ts = $request->get('ts');
        //判断是否是h5
        $js_sdk = $request->get('is_jsdk', 0);

        if (!$p || !$ts) {
            $this->returnError(REQUEST_PARAMETER_ERROR);
        }

        if (1 != $js_sdk) {
            $d = ModAuth::dencrypt($p, $ts, self::auth_pos);
            $this->params = json_decode($d['d'], true); // 获取真实数据
        } else {
            $d = ModAuthJs::requestDecrypt($p, $ts);
            if ($d && isset($d['d'])) {
                $request->merge(['p_param' => json_decode($d['d'], true)]);
            } else {
                $request->merge(['p_param' => null]);
            }
        }

        if ($request->set('p')) {
            // 可以返回一个错误响应或者重定向到其他页面
            $this->returnError(REQUEST_PARAMETER_ERROR);
        }
//        Crypt::encrypt()
        return $next($request);
    }


}
